import { ChangeDetectorRef, Component, DestroyRef, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { finalize } from 'rxjs';

import { ActionCode } from '@app/config/actionCode';
import { RequestParams } from '@app/core/domain/request-params';
import { Role, RoleService } from '@app/core/services/http/system/role.service';
import { OptionsInterface } from '@app/core/services/types';
import { AntTableConfig, AntTableComponent } from '@app/shared/components/ant-table/ant-table.component';
import { PageHeaderType } from '@app/shared/components/page-header/page-header.component';
import { SharedModule } from '@app/shared/shared.module';
import { ModalBtnStatus } from '@app/widget/base-modal';
import { RoleManageModalService } from '@app/widget/biz-widget/system/role-manage-modal/role-manage-modal.service';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

interface PageSearchParam {
  roleName: string;
}

@Component({
  selector: 'app-role-manager',
  standalone: true,
  imports: [SharedModule, AntTableComponent],
  templateUrl: './role-manager.component.html',
  styleUrl: './role-manager.component.less'
})
export class RoleManagerComponent implements OnInit {
  @ViewChild('zorroIconTpl', { static: true }) zorroIconTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('aliIconTpl', { static: true }) aliIconTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('operationTpl', { static: true }) operationTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('visibleTpl', { static: true }) visibleTpl!: TemplateRef<NzSafeAny>;
  @ViewChild('newLinkFlag', { static: true }) newLinkFlag!: TemplateRef<NzSafeAny>;

  ActionCode = ActionCode;
  checkedCashArray = [];
  pageSearchParam: Partial<PageSearchParam> = {};
  tableConfig!: AntTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '角色管理',
    breadcrumb: ['首页', '功能菜单', '角色管理']
  };
  dataList: Role[] = [];
  visibleOptions: OptionsInterface[] = [];

  constructor(
    private readonly destroyRef: DestroyRef,
    private readonly modalService: RoleManageModalService,
    private readonly roleService: RoleService,
    private readonly modalSrv: NzModalService,
    private readonly message: NzMessageService,
    private readonly cdr: ChangeDetectorRef,
    private readonly router: Router
  ) {}

  selectedChecked(e: NzSafeAny): void {
    // @ts-ignore
    this.checkedCashArray = [...e];
  }

  reloadTable(): void {
    this.message.info('刷新成功');
    this.getDataList();
  }

  resetForm(): void {
    this.pageSearchParam = {};
    this.getDataList();
  }

  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  appendRequestParams(): RequestParams {
    const filter: Partial<Role> = {};
    let requestParams: RequestParams = {
      '@relationships': 'all',
      current: this.tableConfig.pageIndex,
      pageSize: this.tableConfig.pageSize,
      '@filter': '',
      ...filter
    };

    if (this.pageSearchParam.roleName) {
      requestParams['@filter'] += `contains(Name,${this.pageSearchParam.roleName})`;
    }

    return requestParams;
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const params: RequestParams = this.appendRequestParams();
    this.roleService
      .getEntityPageList(params)
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(data => {
        const { records, total, pages } = data;
        this.dataList = [...records];
        this.tableConfig.total = total!;
        this.tableConfig.pageIndex = pages!;
        this.tableLoading(false);
        this.checkedCashArray = [...this.checkedCashArray];
      });
  }

  setRole(id: number): void {
    this.router.navigate(['/default/systemManage/role/set-role'], { queryParams: { id: id } });
  }

  add(): void {
    this.modalService
      .show({ nzTitle: '新增' })
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(res => {
        if (!res || res.status === ModalBtnStatus.Cancel) {
          return;
        }
        const param = { ...res.modalValue };
        this.tableLoading(true);
        this.addEditData(param, 'addEntity');
      });
  }

  edit(id: number, dataItem: Role): void {
    console.log(dataItem);
    this.roleService
      .getEntityById(id)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(res => {
        this.modalService
          .show({ nzTitle: '编辑' }, res[0])
          .pipe(
            finalize(() => {
              this.tableLoading(false);
            }),
            takeUntilDestroyed(this.destroyRef)
          )
          .subscribe(({ modalValue, status }) => {
            if (status === ModalBtnStatus.Cancel) {
              return;
            }
            modalValue.id = id;
            this.tableLoading(true);
            this.addEditData(modalValue, 'editEntity');
          });
      });
  }

  addEditData(param: Role, methodName: 'editEntity' | 'addEntity'): void {
    this.roleService[methodName]([param])
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => {
        this.getDataList();
      });
  }

  del(id: number): void {
    const ids: number[] = [id];
    this.modalSrv.confirm({
      nzTitle: '确定要删除吗？',
      nzContent: '删除后不可恢复',
      nzOnOk: () => {
        this.tableLoading(true);
        this.roleService
          .delEntities(ids)
          .pipe(
            finalize(() => {
              this.tableLoading(false);
            }),
            takeUntilDestroyed(this.destroyRef)
          )
          .subscribe(() => {
            if (this.dataList.length === 1) {
              this.tableConfig.pageIndex--;
            }
            this.getDataList();
          });
      }
    });
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: false,
      headers: [
        {
          title: '角色名称',
          field: 'name',
          width: 100
        },
        {
          title: '备注',
          width: 100,
          field: 'roledesc'
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 150,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1
    };
  }

  ngOnInit(): void {
    this.initTable();
  }
}
